package com.taxshare.jwt;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
public class JwtHelper {

    /**
     * 密钥加密token
     */
    public static String generateToken(JwtInfo jwtInfo, int expire) throws Exception {
        String compactJws = Jwts.builder()
                .setSubject(jwtInfo.getUserLoginName())
                .claim(JwtConstant.JWT_KEY_USER_ID, jwtInfo.getUserId())
                .claim(JwtConstant.JWT_KEY_USER_NICK_NAME, jwtInfo.getUserNickName())
                .claim(JwtConstant.JWT_KEY_USER_TYPE, jwtInfo.getUserType())
                .claim(JwtConstant.JWT_KEY_TENANT_ID, jwtInfo.getTenantId())
                .claim(JwtConstant.JWT_KEY_ROLE_ID, jwtInfo.getRoleId())
                .claim(JwtConstant.JWT_KEY_EXPAND_INFO, jwtInfo.getExpandField())
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, RsaKeyHelper.getKey(RsaKeyHelper.PRIVATE_KEY_FILE))
                .compact();
        return compactJws;
    }

    /**
     * 公钥解密token中的用户信息
     */
    public static JwtInfo getInfoFromToken(String token) throws Exception {
        Jws<Claims> claimsJws = parserToken(token);
        Claims body = claimsJws.getBody();
        //用户信息对象
        JwtInfo info = new JwtInfo();
        //登陆的用户名称
        String userLoginName = StringHelper.getObjectValue(body.getSubject());
        //用户userId
        String userId = StringHelper.getObjectValue(body.get(JwtConstant.JWT_KEY_USER_ID));
        //姓名nickname
        String nickName = StringHelper.getObjectValue(body.get(JwtConstant.JWT_KEY_USER_NICK_NAME));
        //用户类型
        String userType = StringHelper.getObjectValue(body.get(JwtConstant.JWT_KEY_USER_TYPE));
        //集团编码
        String tenantId = StringHelper.getObjectValue(body.get(JwtConstant.JWT_KEY_TENANT_ID));
        //角色编码
        String roleId = StringHelper
                .getObjectValue(body.get(JwtConstant.JWT_KEY_ROLE_ID));
        //设置信息
        info.setUserLoginName(userLoginName);
        info.setUserId(userId);
        info.setUserNickName(nickName);
        info.setUserType(userType);
        info.setTenantId(tenantId);
        info.setRoleId(roleId);
        //拓展信息字段
        Object obj = body.get(JwtConstant.JWT_KEY_EXPAND_INFO);
        if (obj != null) {
            info.setExpandField((Map<String, Object>) obj);
        } else {
            info.setExpandField(new HashMap());
        }
        return info;
    }

    /**
     * 公钥解析token
     */
    public static Jws<Claims> parserToken(String token) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser()
                .setSigningKey(RsaKeyHelper.getKey(RsaKeyHelper.PUBLIC_KEY_FILE)).parseClaimsJws(token);
        return claimsJws;
    }

}
